<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ES6 Promise</title>
</head>
<body>
  
</body>
<script>
  function myPromise(executor) {
    let self = this;
    self.status = 'pending';
    self.value = null;
    self.reason = null;

    self.onFulfilledCallbacks = [];
    self.onRejectedCallbacks = [];

    // 成功
    function resolve(value) {
      if (self.status === 'pending') {
        self.value = value; // 保存成功的结果
        self.status = 'fulfilled'; // 修改状态为完成

        self.onFulfilledCallbacks.forEach(item => item(value))
      }
    }

    // 失败
    function reject(reason) {
      if (self.status === 'pending') {
        self.reason = reason; // 失败原因
        self.status = 'rejected'

        self.onRejectedCallbacks.forEach(item => item(reason))
      }
    }

    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err)
    }
  }


  // 挂载一个全局的then方法
  myPromise.prototype.then = function(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ?
    onFulfilled : function(data) { resolve(data) }

    onRejected = typeof onRejected === 'function' ?
    onRejected : function(err) { throw err }

    let self = this;
    if (self.status === 'pending') {
      self.onFulfilledCallbacks.push(onFulfilled)
      self.onRejectedCallbacks.push(onRejected)
    }
  }

  let demo = new myPromise((resolve, reject) => {
    console.log('promise success')

    setTimeout(() => {
      resolve('异步结果返回')
    }, 2000)
  })

  demo.then(data => console.log(data))

</script>
</html>